package com.zy.pro.order.web;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.core.model.PageView;
import com.zy.core.web.BaseController;
import com.zy.pro.city.model.City;
import com.zy.pro.city.service.CityService;
import com.zy.pro.city.web.form.CitySearchForm;
import com.zy.pro.letter.model.Letter;
import com.zy.pro.order.OrderCnt;
import com.zy.pro.order.model.OrderItem;
import com.zy.pro.order.service.OrderItemService;
import com.zy.pro.order.web.form.OrderItemSearchForm;
import com.zy.pro.shop.model.Shop;
import com.zy.pro.shop.service.ShopService;
import com.zy.pro.system.web.form.MenuForm;
import com.zy.pro.user.model.User;
import com.zy.pro.user.service.UserService;
import com.zy.utils.DateHelp;
import com.zy.utils.DateUtil;
import com.zy.utils.SessionUtils;
import com.zy.utils.UUIDHelper;
/**
 * 订单管理控制器
 *
 */
@Controller
@RequestMapping("/control/order/orderItemController")
public class OrderItemController extends BaseController {

	private static final Logger logger = Logger.getLogger(OrderItemController.class);
	
	/**
	 * 订单管理服务类
	 */
	@Resource(name = "orderItemServiceImpl")
	private OrderItemService orderItemService;
	
	/**
	 * 城市管理服务类
	 */
	@Resource(name = "cityServiceImpl")
	private CityService cityService;
	
	/**
	 * 店铺管理服务类
	 */
	@Resource(name = "shopServiceImpl")
	private ShopService shopService;
	
	/**
	 * 系统管理员管理服务类
	 */
	@Resource(name = "userServiceImpl")
	private UserService userService;
	
	/**
	 * 业主登录后 - 下预约订单
	 * @param orderItem
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping("/userAddOrder")
	@ResponseBody	//返回json类型对象,需要添加响应body的注释
	public JSON userAddOrder(OrderItem orderItem,String orderTimeStr,HttpServletRequest request,ModelMap map,HttpServletResponse response){
		/*response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");*/
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			/*PrintWriter out;
			out = response.getWriter();*/
			//预约时间
			orderItem.setOrderTime(DateHelp.fmtStrToDate(orderTimeStr, "yyyy-MM-dd"));
			//设置订单号
			orderItem.setOrderId(DateUtil.fmtDateToStr(new Date()));
			//订单生成时间
			orderItem.setOrderCreateTime(new Date());
			//总订单状态1:正常(未执行,对支付状态1),2:正常(执行中,对支付状态2,3,4,5),3:删除(此状态为3,表示店铺/用户都不展示,都删除状态),4:执行完成(确认完成的订单,对支付状态5,6,7)
			orderItem.setOrderStatus(1);
			//用户订单状态(1:正常,2:冻结,3:删除)
			orderItem.setOrderUserStatus(1);
			//店铺订单状态(1:正常,2:冻结,3:删除)
			orderItem.setOrderShopStatus(1);
			//金额支付状态1:未支付,2:待支付,3:部分支付,4:全部支付,5:已完成,6:已评论,7:已退款
			orderItem.setOrderMoneyStatus(OrderCnt.ORDER_MONEY_STAR_STATUS);
			/*//设置城市主键
			Shop shop = shopService.find(orderItem.getOrderShopId());
			orderItem.setOrderCityId(shop.getCityId());*/
			//保存订单
			orderItemService.save(orderItem);
			
			obj.put("status", "y");
			obj.put("info", orderItem.getOrderId());
			
			return obj;
			/*out.print("success");*/
		} catch (Exception e) {
			logger.error(e);
			return null;
		}
	}
	
	/**
	 * 用户中心 - 未执行预约订单列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/userOrderList")
	public String userOrderList(OrderItemSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_ORDER,MenuForm.SUB_TYPE_USER_ORDER_LIST);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("orderCreateTime", "desc");
			//未执行订单(订单状态1)
			form.setOrderStatus(1);
			//创建页面对象
			PageView<OrderItem> pageView = new PageView<OrderItem>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(orderItemService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/order/orderItemController/userOrderList.do?orderUserId="+form.getOrderUserId());
		
			return "/control/jsp/user/user_o1";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	
	/**
	 * 用户中心 - 执行中(待付款,部分付款,全部付款)预约订单列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/userOrderExecutionList")
	public String userOrderExecutionList(OrderItemSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_ORDER,MenuForm.SUB_TYPE_USER_ORDER_EXE_LIST);
			map.addAttribute("menuForm", menuForm);
			form.getOrderby().put("orderCreateTime", "desc");
			//执行中订单(订单状态2)
			form.setOrderStatus(2);
			//创建页面对象
			PageView<OrderItem> pageView = new PageView<OrderItem>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(orderItemService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/order/orderItemController/userOrderExecutionList.do?orderUserId="+form.getOrderUserId());
		
			return "/control/jsp/user/user_o2";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	/**
	 * 用户中心 - 已完成(已完成,已评价,已退款)预约订单列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/userOrderCompleteList")
	public String userOrderCompleteList(OrderItemSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_ORDER,MenuForm.SUB_TYPE_USER_ORDER_COM_LIST);
			map.addAttribute("menuForm", menuForm);
			form.getOrderby().put("orderCreateTime", "desc");
			//已完成订单(订单状态4)
			form.setOrderStatus(4);
			//订单用户状态(1:正常,3:删除)
			form.setOrderUserStatus(1);
			//创建页面对象
			PageView<OrderItem> pageView = new PageView<OrderItem>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(orderItemService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/order/orderItemController/userOrderCompleteList.do?orderUserId="+form.getOrderUserId());
		
			return "/control/jsp/user/user_o3";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	/**
	 * 用户中心-删除单个订单管理(用户删除订单不需要通知店铺)
	 */
	@RequestMapping("/userDeletedOrder")
	public void userDeletedOrder(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			PrintWriter out;
			out = response.getWriter();
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				if(o.getOrderStatus() == 1){
					//判断未执行的订单,直接删除 总的订单状态,表示同时删除 用户和店铺 两边的记录
					order.setOrderStatus(3);//1:未执行,2:执行中,3:删除状态,4:已完成
					orderItemService.updateBySelective(order);
				}else if(o.getOrderStatus() == 2){
					//判断如果是刚执行中,未支付的订单
					orderItemService.updateOrderAndLetterShop(form);
				}else if(o.getOrderStatus() == 4){
					//判断已完成的订单,只删除用户自己的记录
					order.setOrderUserStatus(3);//1:正常,3:删除
					orderItemService.updateBySelective(order);
				}
				out.print("true");
			}else{
				out.print("false");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	} 
	
	/**
	 * 用户中心 - 用户确认订单已完成,修改订单支付状态为 5:已完成,修改订单状态为 4:已完成
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/userConfirmOrder")
	public void userConfirmdOrder(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			PrintWriter out;
			out = response.getWriter();
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				//设置订单支付状态 '已完成' 状态
				order.setOrderMoneyStatus(OrderCnt.ORDER_MONEY_COMEPLETE_STATUS);
				//设置订单状态为 '已完成' 状态(1:未执行,2:执行中,3:已删除,4:已经完成)
				order.setOrderStatus(4);
				orderItemService.updateBySelective(order);
				out.print("true");
			}else{
				out.print("false");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/**
	 * 用户中心 - 用户付款,并发送站内信通知卖家
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/userPayment")
	@ResponseBody
	public JSON userPayment(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				orderItemService.userPayment(form);
				obj.put("status", "y");//状态
				obj.put("info", form.getOrderId());//返回内容
			}
			return obj;
		} catch (Exception e) {
			logger.error(e);
			return obj;
		}
	}
	
	/**
	 * 用户中心 - 申请退款,并发送站内信通知卖家
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/userApplyRefund")
	/*@ResponseBody
	public JSON userApplyRefund(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				orderItemService.userApplyRefund(form);
				obj.put("status", "y");//状态
				obj.put("info", form.getOrderId());//返回内容
			}
			return obj;
		} catch (Exception e) {
			logger.error(e);
			return obj;
		}
	}*/
	public void userApplyRefund(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			PrintWriter out;
			out = response.getWriter();
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				orderItemService.userApplyRefund(form);
				out.print("true");
			}else{
				out.print("false");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/**
	 * 用户中心 - 用户确认退款成功
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/userConfirmRefund")
	public void userConfirmRefund(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			PrintWriter out;
			out = response.getWriter();
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				//设置订单支付状态 '已退款' 状态
				order.setOrderMoneyStatus(OrderCnt.ORDER_MONEY_REFUND_STATUS);
				//设置订单状态为 '已完成' 状态(1:未执行,2:执行中,3:已删除,4:已经完成)
				order.setOrderStatus(4);
				//设置订单用户状态为'正常'状态(1:正常,2:申请退款,3:删除)
				//order.setOrderUserStatus(1);
				orderItemService.updateBySelective(order);
				out.print("true");
			}else{
				out.print("false");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/************************************end 用户中心*******************************************/
	/************************************start 卖家中心*******************************************/
	
	/**
	 * 卖家中心 - 未执行(用户刚下单)预约订单列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/shopOrderList")
	public String shopOrderList(OrderItemSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_ORDER,MenuForm.SUB_TYPE_SELLER_ORDER_LIST);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("orderCreateTime", "desc");
			//未执行订单(订单状态1)
			form.setOrderStatus(1);
			//创建页面对象
			PageView<OrderItem> pageView = new PageView<OrderItem>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(orderItemService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/order/orderItemController/shopOrderList.do?orderShopId="+form.getOrderShopId());
			
			return "/control/jsp/seller/order_y";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	/**
	 * 卖家中心 - 执行中预约订单列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/shopOrderExecutionList")
	public String shopOrderExecutionList(OrderItemSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_ORDER,MenuForm.SUB_TYPE_SELLER_ORDER_EXE);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("orderCreateTime", "desc");
			//执行中订单(订单状态2)
			form.setOrderStatus(2);
			//创建页面对象
			PageView<OrderItem> pageView = new PageView<OrderItem>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(orderItemService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/order/orderItemController/shopOrderExecutionList.do?orderShopId="+form.getOrderShopId());
			
			return "/control/jsp/seller/order_z";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	/**
	 * 卖家中心 - 已完成(已完成/已评价/已退款的)预约订单列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/shopOrderCompleteList")
	public String shopOrderCompleteList(OrderItemSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_ORDER,MenuForm.SUB_TYPE_SELLER_ORDER_COM);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("orderCreateTime", "desc");
			//已完成订单(订单状态4)
			form.setOrderStatus(4);
			//订单店铺状态(1:正常,3:删除)
			form.setOrderShopStatus(1);
			//创建页面对象
			PageView<OrderItem> pageView = new PageView<OrderItem>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(orderItemService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/order/orderItemController/shopOrderCompleteList.do?orderShopId="+form.getOrderShopId());
			
			return "/control/jsp/seller/order_f";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	/**
	 * 卖家中心-删除单个订单管理
	 * 卖家删除未执行的订单时,需要发送站内信通知用户
	 * 删除未执行的订单时,需要传入店铺主键,用户主键,订单主键
	 * 卖家删除已完成的订单时,只删除卖家自己的记录(传入订单主键)
	 */
	@RequestMapping("/shopDeletedOrder")
	public void shopDeletedOrder(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			PrintWriter out;
			out = response.getWriter();
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				if(o.getOrderStatus() == 1){
					//判断未执行的订单,直接删除 总的订单状态,表示同时删除 用户和店铺 两边的记录,同时发送站内信通知用户!
					orderItemService.updateOrderAddLetter(form);
				}else if(o.getOrderStatus() == 4){
					//判断已完成的订单,只删除卖家自己的记录S
					order.setOrderShopStatus(3);//1:正常,3:删除
					orderItemService.updateBySelective(order);
				}
				out.print("true");
			}else{
				out.print("false");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/**
	 * 卖家中心 - 确认订单总金额并执行订单
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/editOrderMoney")
	@ResponseBody
	public JSON editOrderMoney(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				//设置订单总金额
				order.setOrderMoney(form.getOrderMoney());
				//设置订单未付金额(初始值等于总金额)
				order.setOrderFailsPayMoney(form.getOrderMoney());
				//设置订单应金额(初始值等于总金额)
				order.setOrderThisMoney(form.getOrderMoney());
				//设置订单支付状态待支付状态
				order.setOrderMoneyStatus(OrderCnt.ORDER_MONEY_TOBE_STATUS);
				//设置订单状态为执行中状态(1:未执行,2:执行中,3:已删除,4:已经完成)
				order.setOrderStatus(2);
				orderItemService.updateBySelective(order);
				obj.put("status", "y");//状态
				obj.put("info", order.getOrderId());//返回内容
			}
			return obj;
		} catch (Exception e) {
			logger.error(e);
			return obj;
		}
	}
	
	/**
	 * 卖家中心 - 设置本次应付款数
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/setOrderThisMoney")
	@ResponseBody
	public JSON setOrderThisMoney(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				//设置订单本次应付款项
				order.setOrderThisMoney(form.getOrderThisMoney());
				orderItemService.updateBySelective(order);
				
				obj.put("status", "y");//状态
				obj.put("info", order.getOrderId());//返回内容
			}
			return obj;
		} catch (Exception e) {
			logger.error(e);
			return obj;
		}
	}
	
	/**
	 * 用户中心/卖家中心 订单详情展示(公用页面,根据传入的用户或者卖家主键在页面上判断引用用户菜单或者卖家菜单)
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/displayOrderDetail")
	public String displayOrderDetail(OrderItemSearchForm form, ModelMap map, HttpServletRequest request){
		try {
			//设置菜单类型
			User user = SessionUtils.getUser(request);
			if(user != null){
				MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_ORDER,0);
				map.addAttribute("menuForm", menuForm);
			}else{
				MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_ORDER,0);
				map.addAttribute("menuForm", menuForm);
			}
			
			OrderItem order = orderItemService.findOrderDetail(form.getOrderId());
			map.addAttribute("order", order);
			map.addAttribute("form", form);
			return "control/jsp/order_detail";
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
	}
	
	/**
	 * 卖家中心 - 卖家设置已退款
	 * @param form
	 * @param map
	 * @param request
	 * @param response
	 */
	@RequestMapping("/shopRefund")
	public void shopRefund(OrderItemSearchForm form, ModelMap map,HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			PrintWriter out;
			out = response.getWriter();
			OrderItem o = orderItemService.find(form.getOrderId());
			if(o != null){
				OrderItem order = new OrderItem();
				order.setOrderId(form.getOrderId());
				//设置订单卖家状态为'已退款'状态(1:正常,2:已退款,3:删除)
				order.setOrderShopStatus(2);
				orderItemService.updateBySelective(order);
				out.print("true");
			}else{
				out.print("false");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
